import { Message, MessageBox, Loading } from 'element-ui'
import { getToken } from "@/utils/auth";
import axios from "axios";
import XLSX from 'xlsx-s'
export default {
  // Excel文件验证
  noXlsx(file) {
    let suffix = file.substr(file.lastIndexOf("."));
    if (".xls" != suffix && ".xlsx" != suffix) {
      Message.warning("选择Excel格式的文件导入！");
      return true;
    } else {
      return false;
    }
  },
  // confirm提示框
  confirm(text, type) {
    return new Promise((resolve, reject) => {
      MessageBox.confirm(text, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: type || ''
      })
        .then(() => resolve())
        .catch(() => {
        })
    })
  },
  //loading
  loading(text) {
    return Loading.service({
      lock: true,
      text: text || '加载中...',
      spinner: 'el-icon-loading'
    })
  },
  // 导出文件（需要token）
  getObjUrl(url, params = {}, name) {
    const loading = Loading.service({
      lock: true,
      text: '导出中...',
      spinner: 'el-icon-loading'
    })
    axios
      .get(url, {
        params: params,
        headers: {
          Authorization: getToken()
        },
        responseType: "blob" //告诉服务器我们需要的响应格式
      })
      .then(res => {
        loading.close()
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel" //将会被放入到blob中的数组内容的MIME类型
        });
        let objectUrl = URL.createObjectURL(blob); //生成一个url
        console.log(objectUrl);
        let link = document.createElement('a')
        link.download = `${name}.xlsx`
        link.href = objectUrl
        link.click()//浏览器打开这个url
      })
      .catch(err => {
        loading.close()
        console.log(err);
        Message.error("导出失败");
      });
  },
  // 导出文件(post)
  postObjUrl(url, data, name) {
    const loading = Loading.service({
      lock: true,
      text: '导出中...',
      spinner: 'el-icon-loading'
    })
    axios.post(url, data, {
      responseType: "blob" //告诉服务器我们需要的响应格式
    }).then(res => {
      loading.close()
      let blob = new Blob([res.data], {
        type: "application/vnd.ms-excel" //将会被放入到blob中的数组内容的MIME类型
      });
      let objectUrl = URL.createObjectURL(blob); //生成一个url
      console.log(objectUrl);
      let link = document.createElement('a')
      link.download = `${name}.xlsx`
      link.href = objectUrl
      link.click()//浏览器打开这个url
    })
      .catch(err => {
        loading.close()
        console.log(err);
        Message.error("导出失败");
      });
  },
  createxlsx({mydata,fileName,dataList,cols=[],type,requireMerge=[],loading}){
    const data = mydata
    const filename = `${fileName}.xlsx`
    const ws_name = 'Sheet1'
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.aoa_to_sheet(data)
    XLSX.utils.book_append_sheet(wb, ws, ws_name)
    ws['!merges'] = this._getMergeRecord(dataList,type,requireMerge)
    ws['!cols'] = cols
    const keys = Object.keys(ws).filter(item => !item.startsWith('!'))
    keys.forEach(key => {
      ws[key].s = {
        alignment: {
          horizontal: 'left',
          vertical: 'center'
        }
      }
    })
    XLSX.writeFile(wb, filename)
    loading.close()
  },
  _getMergeRecord(resData,type,requireMerge) {
    // 总的要合并的
    const total = []

    let currentId = null
    let tempIndexArr = []

    // 循环整个，记录一样的的下标
    for (let index = 0; index < resData.length; index++) {
      if (currentId === null) {
        // 第一次如果没有，就赋值
        currentId = resData[index][type]
        tempIndexArr.push(index)
      } else {
        // 如果有
        if (currentId === resData[index][type]) {
          // 并且一样
          // 应该把下标存入临时数组，到时再取头和尾
          tempIndexArr.push(index)

          // 如果是最后一个
          if (index === resData.length - 1) {
            // 直接处理
            if (tempIndexArr.length > 1) {
              const start = tempIndexArr[0]
              const end = tempIndexArr[ tempIndexArr.length - 1 ]
              total.push(
                this._getMergeConfig(start, end,requireMerge)
              )
            }
          }
        } else {
          // 如果不一样，并且数组里有1个以上的元素
          if (tempIndexArr.length > 1) {
            const start = tempIndexArr[0]
            const end = tempIndexArr[ tempIndexArr.length - 1 ]
            total.push(
              this._getMergeConfig(start, end,requireMerge)
            )
          }

          // 并且不一样
          // 直接赋值带过
          currentId = resData[index][type]
          tempIndexArr = [ index ]
        }
      }
    }
    return this.flatten(total)
  },
  _getMergeConfig(start, end,requireMerge) {
    // + 1是因为表头也算一行
    return requireMerge.map(item => ({
      s: {
        c: item,
        r: start + 1
      },
      e: {
        c: item,
        r: end + 1
      }
    }))
  },
  flatten(arr) {
    return arr.reduce((result, item) => {
      return result.concat(Array.isArray(item) ? this.flatten(item) : item)
    }, [])
  }
}
